package com.example.hotel_lxy.ui.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.hotel_lxy.R;
import com.example.hotel_lxy.bean.AnniversaryBean;
import com.example.hotel_lxy.bean.BeanBean;
import com.example.hotel_lxy.bean.DialogAnniversaryBean;
import com.example.hotel_lxy.bean.EventBusBean;
import com.example.hotel_lxy.net.Api;
import com.example.hotel_lxy.ui.activity.AnniversaryActivity;
import com.example.hotel_lxy.ui.activity.LoginActivity;
import com.example.hotel_lxy.ui.main.CalendarActivity;
import com.example.hotel_lxy.utils.SPUtils;
import com.ysxsoft.common_base.base.RBaseAdapter;
import com.ysxsoft.common_base.base.RViewHolder;
import com.ysxsoft.common_base.utils.DisplayUtils;
import com.ysxsoft.common_base.utils.JsonUtils;
import com.ysxsoft.common_base.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;


/**
* 创建纪念日
* create by Sincerly on 9999/9/9 0009
**/
public class AddAnniversaryDialog extends Dialog {
    private Context mContext;
    private ImageView img_detele;
    private TextView text_add;
    private String id_gx,id_lx;
    private TextView text_relationship,text_type,text_time;
    private PopupWindow mpopup_pending_type;
    private PopupWindow mpopup_all_type;
    private static String id;
    List<DialogAnniversaryBean.DataBean.IdentityBean> identity ;
    List<DialogAnniversaryBean.DataBean.TypeBean> type;
    public AddAnniversaryDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
        this.mContext = context;
        init();
    }

    private View init() {
        View view = View.inflate(mContext, R.layout.dialog_add_anniversary, null);
        img_detele=view.findViewById(R.id.img_detele);
        text_add=view.findViewById(R.id.text_add);
        text_relationship=view.findViewById(R.id.text_relationship);
        text_type=view.findViewById(R.id.text_type);
        text_time=view.findViewById(R.id.text_time);
        img_detele.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        text_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDataAdd();

            }
        });
        text_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CalendarActivity.start(1);
            }
        });
        text_relationship.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopwindowPendingOffice();
            }
        });
        text_type.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopwindowAllType();
            }
        });
        initShowData();
        return view;
    }

    private void initShowData() {
        OkHttpUtils.post()
                .url(Api.POST_ANNIVERSARY)
                .addHeader("flag", SPUtils.get(mContext, "token", "").toString())
                .addParams("type",   "2")
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "查看类型onError   " + e.getMessage());

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "查看类型onResponse   " + response);
                        BeanBean beanBean= JsonUtils.parseByGson(response, BeanBean.class);
                        if(beanBean.getCode().equals("4")){
                            SPUtils.put(mContext,"token","");
                            Intent intent = new Intent(mContext, LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            mContext.startActivity(intent);
                            return;
                        }
                        DialogAnniversaryBean dialogAnniversaryBean = JsonUtils.parseByGson(response, DialogAnniversaryBean.class);
                        if(beanBean.getCode().equals("0")){
                             identity = dialogAnniversaryBean.getData().getIdentity();
                            type = dialogAnniversaryBean.getData().getType();
                        }
                    }
                });
    }

    private void showDataAdd() {
        OkHttpUtils.post()
                .url(Api.POST_INCREASE)
                .addHeader("flag", SPUtils.get(mContext, "token", "").toString())
                .addParams("id",   id)
                .addParams("rid",id_gx)
                .addParams("mid",id_lx)
                .addParams("day",text_time.getText().toString())
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "新增纪念日onError   " + e.getMessage());

                    }
                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "新增纪念日onResponse   " + response);
                        BeanBean beanBean = JsonUtils.parseByGson(response, BeanBean.class);
                        if(beanBean.getCode().equals("0")){
                            listener.onPositiveClick("1");
                            dismiss();
                        }else if(beanBean.getCode().equals("4")){
                            SPUtils.put(mContext,"token","");
                            Intent intent = new Intent(mContext, LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            mContext.startActivity(intent);
                        }
                        else{
                            ToastUtils.show(mContext,beanBean.getMsg());
                            dismiss();
                        }


                    }
                });
    }

    //关系
    private void showPopwindowPendingOffice() {
        View popview =getLayoutInflater().inflate(R.layout.item_popwindow,null);
        RecyclerView recyclerView=popview.findViewById(R.id.rv_pop_info);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        RBaseAdapter<DialogAnniversaryBean.DataBean.IdentityBean> rBaseAdapterPendingOffice = new RBaseAdapter<DialogAnniversaryBean.DataBean.IdentityBean>(getContext(),
                R.layout.item_item_popwindow, identity) {
            @Override
            protected void fillItem(RViewHolder holder, DialogAnniversaryBean.DataBean.IdentityBean item, int position) {
                TextView text_title=holder.itemView.findViewById(R.id.text_title);
                text_title.setText(item.getName());
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        text_relationship.setText(item.getName());
                        id_gx=item.getId()+"";
                        mpopup_pending_type.dismiss();
                    }
                });
            }
            @Override
            protected int getViewType(DialogAnniversaryBean.DataBean.IdentityBean item, int position) {
                return 0;
            }
        };
        recyclerView.setAdapter(rBaseAdapterPendingOffice);
        mpopup_pending_type=new PopupWindow(popview,text_relationship.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT);
        mpopup_pending_type.setOutsideTouchable(true);
        mpopup_pending_type.setFocusable(true);
        mpopup_pending_type.showAsDropDown(text_relationship);

    }

    //类型
    private void showPopwindowAllType() {
        View popview =getLayoutInflater().inflate(R.layout.item_popwindow,null);
        RecyclerView recyclerView=popview.findViewById(R.id.rv_pop_info);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        RBaseAdapter<DialogAnniversaryBean.DataBean.TypeBean> rBaseAdapterAllType = new RBaseAdapter<DialogAnniversaryBean.DataBean.TypeBean>(getContext(),
                R.layout.item_item_popwindow, type) {
            @Override
            protected void fillItem(RViewHolder holder, DialogAnniversaryBean.DataBean.TypeBean item, int position) {
                TextView text_title=holder.itemView.findViewById(R.id.text_title);
                text_title.setText(item.getName());
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        text_type.setText(item.getName());
                        id_lx=item.getId()+"";
                        mpopup_all_type.dismiss();
                    }
                });
            }

            @Override
            protected int getViewType(DialogAnniversaryBean.DataBean.TypeBean item, int position) {
                return 0;
            }
        };
        recyclerView.setAdapter(rBaseAdapterAllType);

        mpopup_all_type=new PopupWindow(popview,text_type.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT);
        mpopup_all_type.setOutsideTouchable(true);
        mpopup_all_type.setFocusable(true);
        mpopup_all_type.showAsDropDown(text_type);

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setCanceledOnTouchOutside(true);
        EventBus.getDefault().register(this);  //事件的注册
        setContentView(init());
    }

    public void showDialog() {
        if (!isShowing()) {
            show();
            WindowManager.LayoutParams lp = getWindow().getAttributes();
//            lp.height = DisplayUtils.getDisplayWidth(mContext) * 5 / 5;
            lp.width = DisplayUtils.getDisplayWidth(mContext) * 8 / 10;
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            getWindow().setAttributes(lp);
            getWindow().setGravity(Gravity.CENTER);
        }
    }

    @Override
    public void dismiss() {
        super.dismiss();
        EventBus.getDefault().unregister(this); //解除注册
    }

    public static AddAnniversaryDialog show(Context context, OnDialogClickListener listener,String ids) {
        AddAnniversaryDialog dialog = new AddAnniversaryDialog(context, R.style.BottomDialogStyle);
        dialog.setListener(listener);
        id=ids;
        dialog.showDialog();
        return dialog;
    }

    public OnDialogClickListener listener;

    public AddAnniversaryDialog setListener(OnDialogClickListener listener) {
        this.listener = listener;
        return this;
    }
    public interface OnDialogClickListener {
        /**
         * 点击确定按钮事件
         */
        public void onPositiveClick(String s);
    }

    // 普通事件的处理
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleEvent(EventBusBean carrier) {
        if(carrier!=null){
            if (carrier.getType() == 1) {
                text_time.setText(""+carrier.getStarttime().replace("-","-"));
            }
        }
    }
}